package com.code2roc.fastboot.system.org.controller;

import com.code2roc.fastboot.model.ZTreeNode;
import com.code2roc.fastboot.system.org.bizlogic.DeptLogic;
import com.code2roc.fastboot.system.org.model.SystemDeptDO;
import com.code2roc.fastboot.system.org.service.ISystemDeptService;
import com.code2roc.fastboot.system.org.service.ISystemUserService;
import com.code2roc.fastboot.model.BaseBootController;
import com.code2roc.fastboot.util.ZTreeBuilder;
import com.code2roc.fastboot.framework.extra.formupdate.UpdateRequestBody;
import com.code2roc.fastboot.framework.model.Result;
import com.code2roc.fastboot.framework.util.ConvertOp;
import com.code2roc.fastboot.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/org/dept")
public class SystemDeptController extends BaseBootController {
    @Autowired
    private ISystemDeptService service;
    @Autowired
    private ISystemUserService userService;
    @Autowired
    private DeptLogic deptLogic;

    @ResponseBody
    @PostMapping("/tree")
    public Object tree(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        List<SystemDeptDO> entityList =  service.selectAllList();
        List<ZTreeNode> treeNodeList = new ArrayList<ZTreeNode>();
        ZTreeNode rootNode = new ZTreeNode();
        rootNode.setId("Top");
        rootNode.setpId("-1");
        rootNode.setName("根");
        rootNode.setOpen(true);
        rootNode.setTopNode(true);
        rootNode.setNocheck(true);
        treeNodeList.add(rootNode);
        for (SystemDeptDO entity:entityList) {
            ZTreeNode node = new ZTreeNode();
            node.setId(entity.getRow_id());
            node.setpId(entity.getParent_id());
            node.setName(entity.getDept_name());
            node.setSotNum(entity.getSort_num());
            node.setTopNode(false);
            treeNodeList.add(node);
        }
        List<ZTreeNode> obj = ZTreeBuilder.BuildTree(treeNodeList);
        return result.add("obj",obj);
    }

    @ResponseBody
    @PostMapping("/list")
    public Object list(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String sql = "1=1";
        HashMap<String, Object> paramMap = new HashMap<>();
        String dept_name = ConvertOp.convert2String(params.get("dept_name"));
        String parent_id = ConvertOp.convert2String(params.get("parent_id"));
        if (parent_id.equals("Top")) {
            if (!StringUtil.isEmpty(dept_name)) {
                sql += " and dept_name like #{dept_name}";
                paramMap.put("dept_name", "%" + dept_name + "%");
            }
        } else {
            String guidString = "";
            List<String> guidList = service.getAllSubDeptIDList(parent_id).stream().distinct().collect(Collectors.toList());
            if (guidList.size() == 0) {
                guidString = "''";
            } else {
                for (int i = 0; i < guidList.size(); i++) {
                    if (i == guidList.size() - 1) {
                        guidString += "'" + guidList.get(i) + "'";
                    } else {
                        guidString += "'" + guidList.get(i) + "',";
                    }
                }
            }
            sql += " and row_id in (" + guidString + ")";

            if (!StringUtil.isEmpty(dept_name)) {
                sql += " and dept_name like #{dept_name}";
                paramMap.put("dept_name", "%" + dept_name + "%");
            }
        }

        List<SystemDeptDO> rows = service.selectPageList("*", sql, "sort_num desc", paramMap);
        int total = service.selectCount(sql, paramMap);
        result.add("rows", rows);
        result.add("total", total);
        return result;
    }

    @ResponseBody
    @PostMapping("/insert")
    @org.springframework.transaction.annotation.Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object insert(@RequestBody SystemDeptDO entity) {
        Result result = Result.okResult();
        deptLogic.insert(entity);
        return result;
    }

    @ResponseBody
    @PostMapping("/detail")
    public Object detail(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String row_id = ConvertOp.convert2String(params.get("row_id"));
        result.add("obj", deptLogic.detail(row_id));
        return result;
    }

    @ResponseBody
    @PostMapping("/update")
    @org.springframework.transaction.annotation.Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object update(@UpdateRequestBody SystemDeptDO entity) {
        Result result = Result.okResult();
        deptLogic.update(entity);
        return result;
    }

    @ResponseBody
    @PostMapping("/batchUpdate")
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object batchUpdate(@UpdateRequestBody List<SystemDeptDO> entityList) {
        Result result = Result.okResult();
        service.batchUpdate(entityList);
        return result;
    }

    @ResponseBody
    @PostMapping("/delete")
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object delete(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String row_id = ConvertOp.convert2String(params.get("row_id"));
        if(service.checkExistSub(row_id)){
            return Result.errorResult().setMsg("存在下级部门");
        }
        if(userService.checkExistUserByeDeptID(row_id)){
            return Result.errorResult().setMsg("存在人员");
        }
        deptLogic.delete(row_id);
        return result;
    }

    @ResponseBody
    @PostMapping("/exportData")
    public Object exportData(@RequestBody List<String> deptIDList) throws Exception {
        Result result = Result.okResult();
        String fileid = deptLogic.exportData(deptIDList);
        result.add("fileid", fileid);
        return result;
    }

    @ResponseBody
    @PostMapping("/importData")
    public Object importData(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        Result result = Result.okResult();
        String errormsg = deptLogic.importData(file.getInputStream());
        if (!StringUtil.isEmpty(errormsg)) {
            return Result.errorResult().setMsg(errormsg);
        }
        return result;
    }
}
